2023/12/232174字符

this

this 指向

  1. 函数预编译过程 --> window
  2. 全局作用域里 --> window
  3. call / apply 可以改变函数运行时 this 指向
  4. obj.func(); func()里面执行的 this 指向 obj
var name = "222";
var a = {
    name : "111",
    say : function () {
        console.log(this.name);  //--> undefined
    }
}
var fun = a.say;
fun();  //--> "222"
a.say();
var b = {
    name: "333",
    say: function (fun) {
        fun();  //--> "111"
    }
}
b.say(a.say);  //--> "222"
b.say = a.say;
b.say();  //--> "333"

当函数作为对象的方法被调用时,对象将作为其this值传递给函数。

arguments.callee 指向函数本身 (不符合 ES5 语法规范)

var num = (function (n) {
    if (n == 1) {
        return 1;
    }
    return n * arguments.callee(n - 1);
}(5))
num;  //--> 120

arguments.caller (不符合 ES5 语法规范)

function test () {
    demo();
}
function demo () {
    console.log(demo.caller);
}
test();  //--> function demo(){}

笔试题

var foo = 123;
function print () {
    this.foo = 234;
    console.log(f00);
}
print();  //--> 234
new print();  //--> 123
var a = 5;
function test () {
    a = 0;
    console.log(a);  //--> 0
    console.log(this.a);  //--> 5
    var a;
    console.log(a);  //--> 0
}
test();
function print () {
    console.log(foo);  //--> undefined
    var foo = 2;
    console.log(foo);  //--> 2
    console.log(hello);  //--> 报错 hello is not defined
}
print();
function print () {
    var test;
    test();  // 不报错
    function test(){
        console.log(1);  //--> 1
    }
}
print();
function print () {
    var x = 1;
    if(x == "1")console.log("one!");  //--> one!
    if(x === "1")console.log("two!");  //--> undefined
}
print();
var bar = {a : "002"};
function print () {
    bar.a = 'a';
    Object.prototype.b = 'b';
    return function inner () {
        console.log(bar.a);  //--> a
        console.log(bar.b);  //--> b
    }
}
print()();